package com.tina.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.tina.entity.ChatMsg;
import com.tina.entity.Member;
import com.tina.entity.MsgVo;
import com.tina.service.ChatService;
import com.tina.service.IChatMsgService;
import com.tina.service.IMemberService;
import com.tina.utils.Constant;
import com.tina.utils.DateUtils;
import com.tina.utils.TimeCountUtil;
import com.tina.vo.ChatType;
import com.tina.vo.ResponseJson;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.MessageFormat;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;
import java.util.Optional;
import java.util.stream.Collectors;

import static java.util.stream.Collectors.toList;

/**
 * @author tina
 */
@Service
@Slf4j
public class ChatServiceImpl implements ChatService {

    @Autowired
    private IChatMsgService chatMsgService;

    @Autowired
    private IMemberService memberService;

    /**
     * 发送消息
     *
     * @param ctx
     * @param message
     */
    private void sendMessage(ChannelHandlerContext ctx, String message) {
        ctx.channel().writeAndFlush(new TextWebSocketFrame(message));
    }


    /**
     * 第一次连接注册
     * 1、把未读取的消息查询返回
     * 2、渲染未读取的数据条数
     * 3、查询全部未读取的数据
     * 4、获取最后发言的消息
     *
     * @param memberId
     * @param ctx
     */
    @Override
    public void register(Integer memberId, ChannelHandlerContext ctx) {
        Constant.onlineUserMap.put(String.valueOf(memberId), ctx);
        List<Member> friendList = getFriendList(memberId);
        String responseJson = new ResponseJson().success()
                .setData("type", ChatType.REGISTER)
                .setData("friendList", friendList)
                .setData("getUnreadMessage", getUnreadMessage(friendList))
                .toString();
        sendMessage(ctx, responseJson);
    }

    /**
     * 好友列表
     *
     * @param memberId
     * @return
     */
    public List<Member> getFriendList(Integer memberId) {
        List<Member> friendList = memberService.getFriendList(memberId);
        for (Member member : friendList) {
            Integer integer = chatMsgService.unreadMessageNum(member.getMemberId(), memberId);
            member.setUnreadMessageFriend(integer);
        }
        // 根据未读取消息排序
        List<Member> collect = friendList.stream().sorted(Comparator.comparingInt(Member::getUnreadMessageFriend).reversed()).collect(toList());
        return collect;
    }

    /**
     * 未读取消息总条数
     *
     * @param collect
     * @return
     */
    public Integer getUnreadMessage(List<Member> collect) {
        return collect.stream().collect(Collectors.summingInt(Member::getUnreadMessageFriend));
    }

    /**
     * 发送消息
     *
     * @param chatMsg
     */
    @Override
    public void singleSend(ChatMsg chatMsg) {
        log.info("chatMsg-> {}", chatMsg);
        ChannelHandlerContext toUserCtx = Constant.onlineUserMap.get(String.valueOf(chatMsg.getAcceptMemberId()));
        ChannelHandlerContext ctx = Constant.onlineUserMap.get(String.valueOf(chatMsg.getSendMemberId()));
        chatMsg.setCreateTime(DateUtils.getTime());
        chatMsgService.insertChatMsg(chatMsg);
        if (toUserCtx == null) {
            log.info("userId为 {} 的会员没有登录！", chatMsg.getAcceptMemberId());
            String responseJson = new ResponseJson()
                    .error(MessageFormat.format("userId为 {0} 的用户没有登录！", chatMsg.getAcceptMemberId()))
                    .setData("type", ChatType.NOT_LOGIN)
                    .toString();
            sendMessage(ctx, responseJson);
        } else {
            List<Member> friendList = getFriendList(chatMsg.getAcceptMemberId());
            String responseJson = new ResponseJson().success()
                    .setData("chatMsg", chatMsg)
                    .setData("type", ChatType.SINGLE_SENDING)
                    .setData("friendList", friendList)
                    .setData("getUnreadMessage", getUnreadMessage(friendList))
                    .toString();
            sendMessage(toUserCtx, responseJson);
        }
    }

    /**
     * 查询聊天记录
     *
     * @param chatMsg
     * @param ctx
     */
    @Override
    public void selectChatMsgSend(ChatMsg chatMsg, ChannelHandlerContext ctx) {
        log.info("chatMsg->{}", chatMsg);
        List<Member> friendList = getFriendList(chatMsg.getSendMemberId());
        List<ChatMsg> chatMsgs = chatMsgService.selectChatMsg(chatMsg);
        chatMsgs.stream().forEach(c -> c.setCreateTime(
                DateUtils.dateTimeToDate(c.getCreateTime()).equals(DateUtils.getDate()) ? DateUtils.fromTime(c.getCreateTime()) : c.getCreateTime())
        );

        chatMsgService.editUnreadMessage(chatMsg);
        String responseJson = new ResponseJson().success()
                .setData("chatMsgs", chatMsgs)
                .setData("type", ChatType.CHAT_LOG)
                .setData("friendList", friendList)
                .setData("getUnreadMessage", getUnreadMessage(friendList))
                .toString();
        sendMessage(ctx, responseJson);
    }


}
